<template>
  <div class="position-container">
    <!-- 顶部操作栏 -->
    <BasicInformation
      title="编辑职位"
      :primary-actions="actions"
      @action="handleAction"
    />

    <!-- 主表单 -->
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <el-card class="form-section">
        <template #header>
          <span class="section-title">职位信息</span>
        </template>

        <el-row :gutter="20">
          <!-- 职位名称 -->
          <el-col :md="12">
            <el-form-item label="职位名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入职位名称"
                clearable
              />
            </el-form-item>
          </el-col>

          <!-- 所属部门（多选） -->
          <el-col :md="12">
            <el-form-item label="所属部门" prop="dids">
              <el-select
                v-model="form.dids"
                multiple
                placeholder="请选择所属部门"
                collapse-tags
              >
                <el-option
                  v-for="dept in departments"
                  :key="dept.id"
                  :label="dept.name"
                  :value="dept.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 权限配置（多选） -->
          <el-col :md="24">
            <el-form-item label="权限配置" prop="pids">
              <el-select
                v-model="form.pids"
                multiple
                placeholder="请选择权限"
                collapse-tags
              >
                <el-option
                  v-for="perm in permissions"
                  :key="perm.id"
                  :label="perm.name"
                  :value="perm.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import type { Department, Permission } from '@/types/rs/Role'
import BasicInformation from '@/public-view/BasicInformation.vue'
import  request  from '@/util/request'
const userInfo = sessionStorage.getItem('user');
const user = userInfo ? JSON.parse(userInfo) : null;

interface RoleForm {
  id?: number
  name: string
  dids: number[]
  pids: number[]
  createUser: string,
  updateUser: string,
}

const form = reactive<RoleForm>({
  id: undefined,
  name: '',
  dids: [],
  pids: [],
  createUser: user.user.name,
  updateUser: user.user.name,
})

const rules = reactive<FormRules<RoleForm>>({
  name: [
    { required: true, message: '职位名称不能为空', trigger: 'blur' },
    { min: 2, max: 30, message: '长度需在 2-30 个字符', trigger: 'blur' }
  ],
  dids: [
    { required: true, type: 'array', min: 1, message: '请至少选择一个部门', trigger: 'change' }
  ],
  pids: [
    { required: true, type: 'array', min: 1, message: '请至少选择一个权限', trigger: 'change' }
  ]
})

const departments = ref<Department[]>([])
const permissions = ref<Permission[]>([])
const actions = [
  { name: 'save', label: '保存修改', type: 'primary' },
  { name: 'reset', label: '重置表单', type: 'warning' }
]
const formRef = ref<FormInstance>()
const route = useRoute()
const router = useRouter()
const idParam = Number(route.params.id)

async function loadOptions() {
  try {
    const [deptRes, permRes] = await Promise.all([
      request.post('/per/dept/getAll'),
      request.get('per/perm/getAll')
    ])
    departments.value = deptRes.data.data || []
    permissions.value = permRes.data.data || []
  } catch (error: any) {
    ElMessage.error('选项加载失败：' + error.message)
  }
}

async function loadRole() {
  try {
    const res = await request.get('per/role/getById', { params: { id: idParam } })
    if (res.data.code === '200' || res.data.code === 200) {
      const data = res.data.data
      form.id = data.id
      form.name = data.name
      // 回显 pids/dids
      form.dids = Array.isArray(data.dids) && data.dids.length > 0
        ? data.dids
        : (Array.isArray(data.departments) ? data.departments.map((d: Department) => d.id) : [])
      form.pids = Array.isArray(data.pids) && data.pids.length > 0
        ? data.pids
        : (Array.isArray(data.permissions) ? data.permissions.map((p: Permission) => p.id) : [])
    } else {
      ElMessage.error('加载职位数据失败')
    }
  } catch (err: any) {
    ElMessage.error('加载失败：' + err.message)
  }
}

onMounted(async () => {
  await loadOptions()
  await loadRole()
})

function handleAction(action: string) {
  if (action === 'save') submitForm()
  else if (action === 'reset') resetForm()
}

async function submitForm() {
  try {
    await formRef.value?.validate()
    const res = await request.post('per/role/update', { ...form })
    if (res.data.code === '200' || res.data.code === 200) {
      ElMessage.success(res.data.message || '修改成功')
      router.back()
    } else {
      throw new Error(res.data.message)
    }
  } catch (err: any) {
    ElMessage.error(err.message || '提交失败')
  }
}

function resetForm() {
  loadRole()
  ElMessage.info('表单已重置')
}
</script>

<style scoped>
.position-container { padding: 20px; }
.form-section { margin-bottom: 20px; }
.section-title { font-size: 16px; font-weight: 600; }
</style>